package com.burningtower.controller;

import com.burningtower.common.Result;
import com.burningtower.entity.User;
import com.burningtower.service.UserService;
import com.burningtower.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService service;

    /**
     *1.登录
     * @param username
     * @param password
     * @param session
     * return Result<UserVo>
     */
    @PostMapping("login.do")
    public Result<UserVo> login(String username, String password ,
                                HttpSession session){
        if(username==null||password==null){
            throw new RuntimeException("用户名或密码错误");
        }
        session.removeAttribute("userId");
        User user = service.login(username, password);
        if(user==null){
            throw new RuntimeException("用户名或密码错误");
        }
        LOGGER.info("用户登录："+user.getUsername());
        session.setAttribute("userId",user.getId());//存入session中
        Result<UserVo> result=new Result<>();
        UserVo vo=new UserVo();//给UserVo赋值
        BeanUtils.copyProperties(user,vo);
        result.setData(vo);
        result.setStatus(0);
        return result;
    }

    /**
     *2.注册
     * @param user
     * return Result<User>
     */
    @PostMapping("register.do")
    public Result register(User user){
        service.add(user);
        LOGGER.info("用户注册: "+user.getUsername());
        Result result =new Result<>();
        result.setStatus(0);
        result.setMsg("校验成功");
        return result;
    }
    /**
     * 3.检查用户名是否有效
     * @param str
     * @param type
     * return Result<User>
     */
    @PostMapping("check_valid.do")
    public Result checkUser(@RequestParam String str,@RequestParam String type){
        if(service.checkUser(str, type)){
            throw new RuntimeException("用户名已存在");
        }
        Result result = new Result<>();
        result.setStatus(0);
        result.setMsg("校验成功");
        return result;
    }

    /**
     * 4.获取登录用户信息
     * @param session
     * return Result<UserVo>
     */
    @PostMapping("get_user_info.do")
    public Result<UserVo> getUserById(HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");//取出当前登录用户的id
        Result<UserVo> result = new Result<>();
        if(userId==null){
            result.setStatus(1);
            result.setMsg("未登录");
            return result;
        }
        User user = service.getUserById(userId);
        UserVo vo=new UserVo();
        BeanUtils.copyProperties(user,vo);

        result.setData(vo);
        result.setStatus(0);
        return result;
    }

    /**
     * 5.忘记密码
     * @param username
     * return Result<String>
     */
    @RequestMapping("forget_get_question.do")
    public Result<String> forgetPwd(String username){
        User user = service.forgetPwd(username);
        if(user==null){
            throw new RuntimeException("用户名不存在！");
        }
        if (user.getQuestion()==null){
            throw new RuntimeException("该用户未设置找回密码问题");
        }
        Result<String> result = new Result<>();
        result.setStatus(0);
        result.setData(user.getQuestion());
        return result;
    }

    /**
     * 6.提交问题答案
     * @param username
     * @param question
     * @param answer
     * @param session
     * return Result
     */
    @PostMapping("forget_check_answer.do")
    public Result<String> forgetCheckAnswer(String username, String question,
                                            String answer,HttpSession session){
        User user = service.forgetCheckAnswer(username, question, answer);
        if(user==null){
            throw new RuntimeException("用户名不存在");
        }
        //输入的问题或者答案和数据库的问题或答案 有不同的时候
        if (!user.getQuestion().equals(question)||!user.getAnswer().equals(answer)){
            throw new RuntimeException("问题回答错误");
        }
        Result result = new Result();
        result.setStatus(0);
        //用UUID产生一个随机数 作为token的返回值
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        result.setData(token);
        session.setAttribute("token",token);//将token存于session中
        session.setAttribute("username",username);
        return result;
    }

    /**
     * 7.忘记密码的重设密码
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @param session
     * return Result<String>
     */
    @PostMapping("forget_reset_password.do")
    public Result<String> forgetQuestion(String username,String passwordNew,
                                         String forgetToken,HttpSession session){
        String token = (String) session.getAttribute("token");
        if (token==null){
            throw new RuntimeException("token已经失效");
        }else if (!token.equals(forgetToken)){
            throw new RuntimeException("修改密码操作失效");
        }
        if(!username.equals(session.getAttribute("username"))){
            throw new RuntimeException("用户名错误");
        }
        //当输入的token值相同的时候 修改密码成功
        service.forgetResetPassword(username,passwordNew);
        LOGGER.info("用户忘记密码，重置成功："+username);
        session.removeAttribute("token");
        session.removeAttribute("username");
        Result<String> result = new Result<>();
        result.setMsg("修改密码成功");
        result.setStatus(0);
        return  result;
    }


    /**
     * 8.登录中状态重置密码
     * @param passwordOld
     * @param passwordNew
     * @param session
     * return Result<User>
     */
    @PostMapping("reset_password.do")
    public Result resetPassword(String passwordOld,String passwordNew,HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        service.resetPassword(userId,passwordOld, passwordNew);

        Result result = new Result<>();
        result.setStatus(0);
        result.setMsg("修改密码成功");
        return result;
    }

    /**
     * 9登录状态更新个人信息
     * @param email
     * @param phone
     * @param question
     * @param answer
     * @param session
     * return Result<User>
     */
    @PostMapping("update_information.do")
    public Result updateInformation(@NotNull String email, @NotNull String phone,
                                    @NotNull String question, @NotNull String answer,
                                    HttpSession session){
        Integer id = (Integer) session.getAttribute("userId");
        if (id==null){
            throw new RuntimeException("用户未登录");
        }
        service.updateInformation(id,email, phone, question, answer);
        Result result = new Result<>();
        result.setStatus(0);
        result.setMsg("更新个人信息成功");
        return result;
    }

    /**
     * 10获取当前登录用户的详细信息，并强制登录
     * @param session
     * return Result<User>
     */
    @PostMapping("get_information.do")
    public Result<User> getInformation(HttpSession session){
        Integer id = (Integer) session.getAttribute("userId");
        if (id==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        User information = service.getInformation(id);
        Result<User> result=new Result<>();
        result.setStatus(0);
        result.setData(information);
        return result;
    }


    /**
     *11退出登录
     * @param session
     * return Result<User>
     */
    @RequestMapping("logout.do")
    public Result logout(HttpSession session){
        try {
            session.removeAttribute("userId");
        }catch (Exception e){
            throw new RuntimeException("服务端异常");
        }
        Result result = new Result<>();
        result.setStatus(0);
        result.setMsg("退出成功");
        return result;
    }
}
